Fix API authentication failure when APP_URL is empty #480
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
Fixes #428
Users reported authentication failures when accessing Log Viewer in production environments where
APP_URLis not configured or doesn't match the actual domain. The issue manifested as:/log-viewer) works fine -Auth::check()returnstrue/log-viewer/api/folders) fail -Auth::check()returnsfalsenullforAuth::user()on API routesRoot Cause
The
EnsureFrontendRequestsAreStatefulmiddleware determines whether to apply session middleware to API requests by checking if the request's referer/origin domain matches the configured stateful domains (derived fromAPP_URL,sanctum.stateful, or defaults likelocalhost).When
APP_URLis empty or doesn't match the production domain:/log-viewer) useswebmiddleware group → session works/log-viewer/api/*) referer check fails → session middleware skipped →Auth::user()isnullThis architecture issue affects users deploying to production without properly configured
APP_URL, which is common in containerized or multi-domain environments.Solution
1. Same-Domain Fallback
Added intelligent fallback logic to
EnsureFrontendRequestsAreStateful::fromFrontend():APP_URLis empty, allow same-domain requests by comparing referer/origin domain with current request domain2. Middleware Resolution with Fallback
Added
resolveMiddleware()helper method that:sanctum.middleware.encrypt_cookies,sanctum.middleware.verify_csrf_token) when availableThis ensures authentication works consistently across web and API routes even when
APP_URLis not configured, while respecting user customizations.Changes
EnsureFrontendRequestsAreStatefulmiddleware with:isSameDomainRequest()method for same-domain validationresolveMiddleware()method for graceful middleware class resolutionApiAuthenticationTest.php) covering:Test Coverage
All 294 tests pass (including 12 new API authentication tests) across PHP 8.1-8.4 and Laravel 9-12.